package org.example.config;


import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;


//Controller请求映射方法统一增强
//实现ResponseBodyAdvice接口，表示对返回对象（作为响应正文）进行增强
@ControllerAdvice
public class AppResponseAdvice implements ResponseBodyAdvice<Object> {
    //是否增强呢？
    //如果一些Controller要增强，一些Controller不增强，就可以使用方法参数来判断
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;//这里表示所有的请求映射方法都增强
    }


    //如何增强响应正文
    //body就是请求映射返回方法的返回值对象
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        Map<String,Object> json = new HashMap<>();
        json.put("ok",true);
        json.put("data",body);
        return json;
    }//ResponseBodyAdvice泛型类，它的类型取决于当前类的返回值类型

}
